package com.lntea.netty.demo.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import org.junit.Test;

public class BufferToTextTest {
    private static final int BSIZE = 1024;
    
    @Test
    public void testBufferToText() throws IOException{
        //未指定字符集写数据
        FileChannel fc = new FileOutputStream("output.txt").getChannel();
        fc.write(ByteBuffer.wrap("some text".getBytes()));
        fc.close();
        
        //未指定字符集读数据
        fc = new FileInputStream("output.txt").getChannel();
        ByteBuffer buf = ByteBuffer.allocate(BSIZE);
        fc.read(buf);
        buf.flip();
        //字符集未设置
        System.out.println(buf.asCharBuffer());
        
        //获取文件默认字符集，使用Charset设置字符集读取
        buf.rewind();
        String encoding = System.getProperty("file.encoding");
        System.out.println("Decoded using " + encoding + " : " + Charset.forName(encoding).decode(buf));
        
        //使用字符集写数据
        fc = new FileOutputStream("output.txt").getChannel();
        //需要使用utf-16BE字符集
        fc.write(ByteBuffer.wrap("some other text".getBytes("utf-16BE")));
        fc.close();
        
        //使用asCharBuffer重新读取
        buf.clear();
        fc = new FileInputStream("output.txt").getChannel();
        fc.read(buf);
        buf.flip();
        System.out.println(buf.asCharBuffer());
        
        //使用CharBuffer写数据
        fc = new FileOutputStream("output.txt").getChannel();
        buf = ByteBuffer.allocate(32);
        buf.asCharBuffer().put("some more text");
        fc.write(buf);
        fc.close();
        
        //使用CharBuffer读数据
        fc = new FileInputStream("output.txt").getChannel();
        buf.clear();
        fc.read(buf);
        buf.flip();
        System.out.println(buf.asCharBuffer());
    }
}
